#include<stdio.h>
#include<string.h>
#include<queue>
#define MAXN 10005
int head[MAXN*2];
struct EdgeNode{
	int to;
	int next;
};
EdgeNode edges[MAXN*2];
int in[MAXN], queue[MAXN], money[MAXN];
int n, ans;
int toposort()
{
	ans = 0;
	memset(money, 0, sizeof(money));
	int i, j;
	int iq = 0;
	for(i = 1; i <= n; i ++){
		if(!in[i]){
			queue[iq++] = i;
		}
	}
	for( i = 0; i < iq; i ++){
		int temp = queue[i];
		ans += money[temp];
		for(j = head[temp]; j != -1; j = edges[j].next){
			if(!--in[edges[j].to]){
				queue[iq++] = edges[j].to;
				money[edges[j].to] = money[temp]+1;//这里是分层次，
			}
		}
	}
	return iq == n;
}
int main()
{
	int m, i, a, b;
	while(scanf("%d%d", &n, &m) == 2){
		memset(head, -1, sizeof(head));
		memset(in, 0, sizeof(in));
		for(i = 0; i < m; i ++){
			scanf("%d%d", &a, &b);
				in[a]++;
				edges[i].to = a;
				edges[i].next = head[b];
				head[b] = i;
		}
		int sum = 888*n;
		int flag = toposort();
		printf("%d\n", flag?sum+ans:-1);
	}
	return 0;
}
 
